package ar.republicagroup.gestion.view;

import ar.republicagroup.gestion.entities.Usuario;
import ar.republicagroup.gestion.services.BolsaChequeServices;
import ar.republicagroup.gestion.services.CalendarioBancarioServices;
import ar.republicagroup.gestion.services.LiquidacionServices;
import ar.republicagroup.gestion.services.UsuarioServices;
import ar.republicagroup.gestion.util.AppSession;
import ar.republicagroup.gestion.util.MyLookAndFeel;
import ar.republicagroup.gestion.util.SpringUtils;
import ar.republicagroup.gestion.util.UserSession;
import ar.republicagroup.gestion.util.Validar;
import ar.republicagroup.gestion.util.helpers.UserInterfaceHelper;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import org.apache.log4j.Logger;

/**
 *
 * @author DIEGOALV
 */
public class frmLogin extends javax.swing.JFrame {

        private static Logger log                     = Logger.getLogger(frmLogin.class);
        UsuarioServices usuarioServices               = (UsuarioServices)SpringUtils.getBean("usuarioServices");
        LiquidacionServices liquidacionServices       = (LiquidacionServices)SpringUtils.getBean("liquidacionServices");
        BolsaChequeServices bolsaChequeServices       = (BolsaChequeServices)SpringUtils.getBean("bolsaChequeServices");
        CalendarioBancarioServices calendarioServices = (CalendarioBancarioServices)SpringUtils.getBean("calendarioBancarioServices");
 
        private Task task;
        
    public frmLogin() {
        initComponents();
        valoresPorDefecto();
        UserInterfaceHelper.centreWindow(this);
    }

    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelContenedor = new javax.swing.JPanel();
        txtUsuario = new javax.swing.JTextField();
        lblImagen = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        btnIngresar = new javax.swing.JButton();
        txtContrasena = new javax.swing.JPasswordField();
        lblErrorUsuario = new javax.swing.JLabel();
        lblErrorContrasena = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("..: Bienvenido a República Group Gestión App :...");
        setResizable(false);

        panelContenedor.setBorder(javax.swing.BorderFactory.createTitledBorder("Acceso al sistema"));

        txtUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtUsuarioKeyPressed(evt);
            }
        });

        lblImagen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/keys.png"))); // NOI18N

        jLabel2.setText("Usuario");

        jLabel3.setText("Contraseña");

        btnIngresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ar/republicagroup/gestion/view/images/arrow.png"))); // NOI18N
        btnIngresar.setText("Ingresar");
        btnIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIngresarActionPerformed(evt);
            }
        });

        txtContrasena.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtContrasenaKeyPressed(evt);
            }
        });

        lblErrorUsuario.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N
        lblErrorUsuario.setForeground(new java.awt.Color(255, 0, 0));
        lblErrorUsuario.setText("jLabel1");

        lblErrorContrasena.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N
        lblErrorContrasena.setForeground(new java.awt.Color(255, 0, 0));
        lblErrorContrasena.setText("jLabel1");

        javax.swing.GroupLayout panelContenedorLayout = new javax.swing.GroupLayout(panelContenedor);
        panelContenedor.setLayout(panelContenedorLayout);
        panelContenedorLayout.setHorizontalGroup(
            panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelContenedorLayout.createSequentialGroup()
                .addGap(99, 99, 99)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(btnIngresar, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
                        .addComponent(txtUsuario)
                        .addComponent(txtContrasena))
                    .addComponent(lblErrorUsuario)
                    .addComponent(lblErrorContrasena))
                .addGap(72, 72, 72)
                .addComponent(lblImagen)
                .addContainerGap(32, Short.MAX_VALUE))
        );
        panelContenedorLayout.setVerticalGroup(
            panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelContenedorLayout.createSequentialGroup()
                .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelContenedorLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lblImagen))
                    .addGroup(panelContenedorLayout.createSequentialGroup()
                        .addGap(39, 39, 39)
                        .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addGap(2, 2, 2)
                        .addComponent(lblErrorUsuario)
                        .addGroup(panelContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(panelContenedorLayout.createSequentialGroup()
                                .addGap(5, 5, 5)
                                .addComponent(jLabel3))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelContenedorLayout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtContrasena, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(2, 2, 2)
                        .addComponent(lblErrorContrasena)
                        .addGap(2, 2, 2)
                        .addComponent(btnIngresar)))
                .addContainerGap(31, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelContenedor, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelContenedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIngresarActionPerformed
      accederAlSistema();            
    }//GEN-LAST:event_btnIngresarActionPerformed

    private void txtUsuarioKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsuarioKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            txtContrasena.requestFocus();
        }
    }//GEN-LAST:event_txtUsuarioKeyPressed

    private void txtContrasenaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtContrasenaKeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            mostrarBarraDeProgresoEIniciarTask();
        }
    }//GEN-LAST:event_txtContrasenaKeyPressed

    public void mostrarBarraDeProgresoEIniciarTask(){
            final BarraDeProgreso barra;
            barra = new BarraDeProgreso(this, false);
            barra.setLocationRelativeTo(this);
            barra.setVisible(true);
            task = new Task();
            task.addPropertyChangeListener(new PropertyChangeListener() {

             @Override
             public void propertyChange(PropertyChangeEvent pcEvt) {
                if (SwingWorker.StateValue.DONE == pcEvt.getNewValue()) {
                   Toolkit.getDefaultToolkit().beep(); 
                   barra.setVisible(false);
                   barra.dispose();            
                }
             }
          });
       
            task.execute();
    }
    
    
    class Task extends SwingWorker<Void, Void> {
        @Override
        public Void doInBackground() throws Exception {
             accederAlSistema();
             return null;
        }

    }
    
    
    
    
    public void accederAlSistema() {
        if(esValidoElFormulario()){   
            Usuario usuario = usuarioServices.validarUsuario(txtUsuario.getText(), encriptarClave(txtContrasena.getPassword()));
            if(usuario != null){
                UserSession.getInstance().setUser_name(usuario.getNombre());
                UserSession.getInstance().setPerfil_id(usuario.getPerfilId().getId());
                UserSession.getInstance().setUser_id(usuario.getId());
                UserSession.getInstance().setLook_and_feel(usuario.getLookAndFeelId().getArchivoProperties());
                AppSession.setFechaDeLiquidacion(calendarioServices.calcularFechaDeLiquidacion());
                AppSession.iniciarImpresora();
                bolsaChequeServices.getChequesToLiquidFromListOfBolsaChequeByCliente(null,AppSession.getFechaDeLiquidacion());
                
                log.info(usuario.getLookAndFeelId().getArchivoProperties());
                log.info("Iniciando sesión : "+UserSession.getInstance().getUser_name());
                                
                try {
                    MyLookAndFeel.setCurrentLookAndFeel(UserSession.getInstance().getLook_and_feel());
                } catch (        ClassNotFoundException | IOException ex) {
                    log.error(ex.getMessage());
                }
                
                SwingUtilities.updateComponentTreeUI(this);
                JOptionPane.showMessageDialog(this, "BIENVENIDO!", "Acceso validado", JOptionPane.INFORMATION_MESSAGE);
                //JOptionPane.showMessageDialog(this,"No se olvide de realizar los pagos de las liquidaciones antes de liquidar, \ndesde el menú -> Reportes -> Cheques liquidados","Importante",JOptionPane.INFORMATION_MESSAGE);
                frmMain main = new frmMain();
                main.setVisible(true);
                this.dispose();
            } else {
                JOptionPane.showMessageDialog(this, "Usuario / Contraseña incorrectos","Error", JOptionPane.ERROR_MESSAGE);
            }
     }
    }
    
    
    private void valoresPorDefecto(){
        lblErrorUsuario.setVisible(false);
        lblErrorContrasena.setVisible(false);        
        txtUsuario.requestFocus();
        UserInterfaceHelper.setJFrameIconImage(this);
    }
    
    public boolean esValidoElFormulario(){
            mensajeDeErrorEnLabel(lblErrorUsuario, "", false);
            mensajeDeErrorEnLabel(lblErrorContrasena, "", false);
            
       
        
        if(Validar.esVacio(txtUsuario.getText()) || Validar.validarVacio(txtUsuario.getText())){
            mensajeDeErrorEnLabel(lblErrorUsuario, "(*) Ingrese su usuario", true);
            txtUsuario.requestFocus();
            return false;
        }
        
       if(Validar.esVacio(new String(txtContrasena.getPassword())) || Validar.validarVacio(new String(txtContrasena.getPassword()))){
           mensajeDeErrorEnLabel(lblErrorContrasena,"(*) Ingrese su contraseña",true); 
           txtContrasena.requestFocus();
           return false;
        }
       
        return true;
 
    }
    
    public void mensajeDeErrorEnLabel(JLabel label,String mensaje,boolean visible){
        label.setText(mensaje);
        label.setVisible(true);
    }
    
    public String encriptarClave(char[] param){
       
        String cadena   = new String(param);
        MessageDigest m;
        String result   = null;
            try {
                m = MessageDigest.getInstance("MD5");
                m.update(cadena.getBytes(), 0, cadena.length());
                result = new BigInteger(1,m.digest()).toString(16);
                } catch (NoSuchAlgorithmException ex) {
               log.error(ex.getMessage());
                }
        return result;
    }
    
    
    
   
    public static void main(String args[]) {
        
        try {                
            MyLookAndFeel.setCurrentLookAndFeel("Aluminium_Small_Font.properties");
        } catch (ClassNotFoundException | IOException ex) {
            log.error(ex.getMessage());
        }
        
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmLogin().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnIngresar;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel lblErrorContrasena;
    private javax.swing.JLabel lblErrorUsuario;
    private javax.swing.JLabel lblImagen;
    private javax.swing.JPanel panelContenedor;
    private javax.swing.JPasswordField txtContrasena;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
}
